package com.augurit.gzcgwsp.zzgqba.web;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jbpm.api.ProcessEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;

import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.wfex.common.util.WfUtilsEX;
import com.augurit.gzcgwsp.zzgqba.entity.YwRqZzgqba;
import com.augurit.gzcgwsp.zzgqba.service.IYwRqZzgqbaService;
import com.augurit.gzcgwsp.zzgqba.web.form.YwRqZzgqbaForm;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.bi.web.form.WfBusTemplateForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.entity.Jbpm4HistTask;
import com.augurit.wf.common.form.WfBusSaveResult;
import com.augurit.wf.common.service.IWfBusClientService;
import com.augurit.wf.common.service.IWfService;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfBusClientAction;
@SuppressWarnings("serial")
@Results({
	@Result(name = CrudActionSupport.RELOAD, location = "yw-rq-zzgqba.action", type = "redirect"),
	@Result(name = CrudActionSupport.SUCCESS, location = "/gzcgwsp/zzgqba/YwRqZzgqbaSqb/YYwRqZzgqbaSqb.jsp"),
	@Result(name = WfConstant.PRINT, location = WfConstant.PRINT_JSP),
	@Result(name = CrudActionSupport.INPUT, location = "/gzcgwsp/zzgqba/YwRqZzgqbaSqb/YwRqZzgqbaSqb-input.jsp")
})
public class YwRqZzgqbaAction extends WfBusClientAction<YwRqZzgqbaForm>{
	
	 private SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 
    @Autowired
    private IWfService wfService;
    @Autowired
    private IWfServiceEX wfServiceEX;
	@Autowired
	private IYwRqZzgqbaService ywRqZzgqbaService;
    @Autowired
    private IWfBusTemplateService wfBusTemplateService;
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private ISysCodeService syscodeService;
    
	private YwRqZzgqbaForm form;
	private Long id;
	private Long[] checkedIds;
	private Page<YwRqZzgqbaForm> page = new Page<YwRqZzgqbaForm>(10);

    public String wfBusSave(){
    	try{
    	String isYsl = super.getParameter("isYsl");
        WfBusInstanceTaskForm task = this.wfBusSave((IWfBusClientService)ywRqZzgqbaService, form, YwRqZzgqba.class.getSimpleName());
        if (StringUtils.isNotBlank(isYsl) && "1".equals(isYsl)) {
//            processEngine.getExecutionService().jumpToActivity(task.getExecutionId(), "jbsl");
        	String executionId =  processEngine.getHistoryService().createHistoryTaskQuery().taskId(task.getTaskInstDbid().toString()).uniqueResult().getExecutionId();
            processEngine.getExecutionService().jumpToActivity(executionId, "cksa");
            ywRqZzgqbaService.changeYslState(form.getId(), 2l);
        }
        if (form.getDfsj() == null) {
            String durationExpression = wfServiceEX.getProcDueExpressIonByTaskInstDbid(task.getTaskInstDbid());
            Date dfsj = wfServiceEX.calculateDueDate(form.getSarq(), durationExpression);
            form.setDfsj(dfsj);
            this.save();
        }
        
        WfUtils.renderWfBusSaveJson(task, form);
    	} catch (Exception e) {
    		WfUtils.renderWfFailtureJson("请检查输入内容长度是否过大!");
  	}
        return null;
    }
    
    public String wfBusYslTuih() throws Exception {
    	ywRqZzgqbaService.changeYslState(form.getId(), 0L);
    	WfBusSaveResult result = new WfBusSaveResult(true, null);
		Struts2Utils.renderJson(result);
        return null;
    }
    
    public String printcz() throws Exception {
        return WfUtilsEX.wfBusPrint(form);
    }

    /**
     * 制文
     * @return
     * @throws Exception
     */
    public String makeDocument() throws Exception {
//        if (StringUtils.isNotBlank(form.getRedHeadFileId())) {
//            String redHeadFilePath = wfBusTemplateService.getPrintTemplatePath(Long.parseLong(form.getRedHeadFileId()));
//            form.setRedHeadFilePath(redHeadFilePath);
//        }
//        String templateCode = getTemplateCode();
//        if(templateCode != null && templateCode.trim().length() > 0){
//            String printTemplatePath = wfBusTemplateService.getPrintTemplatePath(templateCode, WfTemplateAttachmentRefForm.ZHENGWEN_TEMPLATE_TYPE);
//            form.setTemplatePath(printTemplatePath);
//            form.setZhengwenPath(wfBusTemplateService.getPrintTemplatePath(templateCode, WfTemplateAttachmentRefForm.ZHENGWEN_FILE_TYPE));
//            
//            WfUtils.wfBusPrint(form);
//            
//            BaseAction.getRequest().setAttribute("entity", OaFawen.class.getSimpleName());
//            BaseAction.getRequest().setAttribute("entityId", id);
//            BaseAction.getRequest().setAttribute("busType", OaFawen.class.getSimpleName());
//        }
        return WfConstant.MAKE_DOCUMENT;
    }
    
	@Override
	public String list() throws Exception {
		ywRqZzgqbaService.search(page, form);
		return SUCCESS;
	}

	/**
	 * �������޸�
	 */
	@Override
	public String input() throws Exception {
        this.initWfOpinions();
        
        getRequest().setAttribute("CurrUserName", this.getLoginUser().getUser().getUserName());
        List<SysCodeForm> sqdwlx = syscodeService.getItems("YW_SQDW_LX");
        List<SysCodeForm> ywHbbm = syscodeService.getItems("ALL_HBBM");
        getRequest().setAttribute("ywhbbm", ywHbbm);
        getRequest().setAttribute("sqdwlx", sqdwlx);
		return INPUT;
	}

	/**
	 * �������������޸ĵ�Form����
	 */
	@Override
	public String save() throws Exception {
		ywRqZzgqbaService.save(form);
		return RELOAD;
	}

	/**
	 * ɾ��һ����¼
	 */
	@Override
	public String delete() throws Exception {
		ywRqZzgqbaService.delete(id);
		return RELOAD;
	}
	
	/**
	 * ɾ�������¼
	 */
	@Override
	public String deleteMore() throws Exception{
		ywRqZzgqbaService.delete(checkedIds);
		return RELOAD;
	}
	
	/**
	 * ׼��ҳ��ģ��
	 */
	@Override
	protected void prepareModel() throws Exception {
		if(id != null){
			form = ywRqZzgqbaService.get(id);
		}
		else
			form = new YwRqZzgqbaForm();
        if (StringUtils.isBlank(form.getAcceptNo())) {
        	String rq = DateUtilsEX.getYearAndMonthAndDay();
        	form.setAcceptNo("gz26"+rq+"XXXXX");
        }
        if (StringUtils.isBlank(form.getSjr())) {
            form.setSjr(this.getLoginUser().getUser().getUserName());
        }
        
        if (StringUtils.isBlank(form.getJbrxm())) {
            form.setJbrxm(this.getLoginUser().getUser().getUserName());
//            form.setJbrxm2(this.getLoginUser().getUser().getUserName());
//            form.setJbrdh(this.getLoginUser().getUser().getOfficeTel());
//            form.setJbrdh2(this.getLoginUser().getUser().getOfficeTel());
        }
        	
//        form.setSajg(this.getLoginUser().getOrg().getOrgName());
//        form.setSajg2(this.getLoginUser().getOrg().getOrgName());
//        form.setSajg3(this.getLoginUser().getOrg().getOrgName());
       // form.setSajg4(this.getLoginUser().getOrg().getOrgName());
    if(StringUtils.isBlank(form.getJbrxm())){
    	form.setJbrxm(this.getLoginUser().getUser().getUserName());
    }
    
//    	form.setJbrxm2(this.getLoginUser().getUser().getUserName());

//    if(StringUtils.isBlank(form.getJbrdh())){
//    	form.setJbrxm(this.getLoginUser().getUser().getUserName());
//    }
//    if(StringUtils.isBlank(form.getJbrdh2())){
//    	form.setJbrxm2(this.getLoginUser().getUser().getUserName());
//    }
    	form.setLarq(new Date());
    	form.setSjsj(new Date());
    	form.setSarq(new Date());
    	
//    	form.setLarq2(new Date());
        
        if (StringUtils.isBlank(form.getCbyw())) {
            WfBusTemplateForm wfBusTemplateForm = wfBusTemplateService.getByTemplateCode(getTemplateCode());
            if (wfBusTemplateForm != null) {
                form.setCbyw(wfBusTemplateForm.getTemplateName());
            }
        }

	        if (StringUtils.isBlank(form.getCbbm())) {
	            form.setCbbm("燃气处");
	        }
        
        try {
            if (form.getSarq() == null) {
                form.setSarq(new Date());
            }
            if (form.getCpsj() == null) {
                form.setCpsj(new Date());
            }
            if (form.getSqrq() == null) {
                form.setSqrq(new Date());
            }
            if (form.getSjsj() == null) {
                form.setSjsj(new Date());
            }
            if(getTaskInstDbid() != null){
            	
            	this.cpbJbrspUtil();
            	this.cpbCldspUtil();
            	this.cpbWldspUtil();
            }
            
        } catch (Exception e) {
            // TODO: handle exception
        }
	}
	
	//打印 呈批表经办人意见
	private void cpbJbrspUtil(){
		String names = "'jbrsl' , 'jbrsj'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer jbrspYj = new StringBuffer();
		for(int i = 0; i < list.size(); i++){
			jbrspYj.append(list.get(i).getHandleComments()).append("\n")
			.append("    ").append(list.get(i).getAssigneeName()).append("\n")
			.append(simpleDateFormat.format(list.get(i).getSignTime())).append("\n");
		}
		form.setCpbJbryj(jbrspYj.toString());
	}
	//打印  呈批表 处领导意见
	private void cpbCldspUtil(){
		String names = "'cfgldsh' , 'czgldsh'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer cldspYj = new StringBuffer();
		for(int i = 0; i < list.size(); i++){
			cldspYj.append(list.get(i).getHandleComments()).append("\n")
			.append("    ").append(list.get(i).getAssigneeName()).append("\n")
			.append(simpleDateFormat.format(list.get(i).getSignTime())).append("\n");
		}
		form.setCpbCldyj(cldspYj.toString());
	}
	//打印  呈批表 委领导意见
	private void cpbWldspUtil(){
		String names = "'wfgldsh' , 'wzgldsp'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer wldspYj = new StringBuffer();
		for(int i = 0; i < list.size(); i++){
			wldspYj.append(list.get(i).getHandleComments()).append("\n")
			.append("    ").append(list.get(i).getAssigneeName()).append("\n")
			.append(simpleDateFormat.format(list.get(i).getSignTime())).append("\n");
		}
		form.setCpbWldyj(wldspYj.toString());
	}
	public YwRqZzgqbaForm getModel() {
		return form;
	}
	
	// ����getter��setter����
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long[] getCheckedIds() {
		return checkedIds;
	}

	public void setCheckedIds(Long[] checkedIds) {
		this.checkedIds = checkedIds;
	}
	
	public Page<YwRqZzgqbaForm> getPage() {
		return page;
	}


	public void setPage(Page<YwRqZzgqbaForm> page) {
		this.page = page;
	}
}
